import React, { useState, useEffect, useMemo } from "react";
import axios from "axios";
import { Sidebar, SidebarItem, Flex } from "react-vant";

interface CityType {
  code: number;
  name: string;
  children?: CityType[];
}

const Index: React.FC = () => {
  const [province, setProvince] = useState<CityType[]>([]);
  const [active, setActive] = useState(0);
  const [active1, setActive1] = useState(0);
  const [active2, setActive2] = useState(0);
  // const
  const city = useMemo(() => {
    if (province.length <= 0) return [];
    return province[active].children as CityType[];
  }, [province, active]);

  const area = useMemo(() => {
    if (province.length <= 0) return [];
    return province[active].children![active1].children as CityType[];
  }, [province, active, active1]);

  const street = useMemo(() => {
    if (province.length <= 0) return [];
    return province[active].children![active1].children![active2].children as CityType[];
  }, [province, active, active1, active2]);



  useEffect(() => {
    axios.get("/api/city").then((resp) => {
      setProvince(resp.data.data);
    });
  }, []);

  return (
    <Flex>
      <Flex.Item span={6}>
        <div className="menu">
          <Sidebar
            value={active}
            onChange={(v) => {
              setActive(v);
              setActive1(0);
              setActive2(0);
            }}
          >
            {province.map((v, i) => {
              return <Sidebar.Item title={v.name} key={i} />;
            })}
          </Sidebar>
        </div>
      </Flex.Item>
      <Flex.Item span={6}>
        <div className="menu">
          <Sidebar
            value={active1}
            onChange={(v) => {
              setActive1(v);
              setActive2(0);
            }}
          >
            {city.map((v, i) => {
              return <Sidebar.Item title={v.name} key={i} />;
            })}
          </Sidebar>
        </div>
      </Flex.Item>
      <Flex.Item span={6}>
        <div className="menu">
          <Sidebar
            value={active2}
            onChange={(v) => {
              setActive2(v);
            }}
          >
            {area.map((v, i) => {
              return <Sidebar.Item title={v.name} key={i} />;
            })}
          </Sidebar>
        </div>
      </Flex.Item>
      <Flex.Item span={6}>
        <div className="menu">
          <Sidebar>
            {street.map((v, i) => {
              return <Sidebar.Item title={v.name} key={i} />;
            })}
          </Sidebar>
        </div>
      </Flex.Item>
    </Flex>
  );
};

export default Index;
